package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    List<User> users = new ArrayList<>();
    @Override
    public List<User> findAll() {
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8","root","123456");

            //3.sql语句
            String sql = "select * from user";

            //4.预编译sql
            preparedStatement = conn.prepareStatement(sql);
            //5.执行sql
            resultSet = preparedStatement.executeQuery();
            //6.遍历user
            while (resultSet.next()) {
                User user = new User(resultSet.getInt("id"),resultSet.getString("name"),resultSet.getString("pass"));
                users.add(user);
            }
            return users;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try{
                //7.关闭资源
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
